import os
from flask import Flask, jsonify
from flask_cors import CORS


def create_app(config_name)->Flask:
    from flask import Flask
    app = Flask(__name__)
    # app.config.from_object(config_name)
    
    if config_name is None:
        print("No config name provided, defaulting to 'development'")
        config_name =  os.environ.get('FLASK_ENV','development')
        
    from config import config
    print(f"Loading config for {config_name}")
    # print(f"{config=}")
    app.config.from_object(config[config_name])
    
    CORS(app,origins=app.config['CORS_ORIGINS'])

    configure_app(app)
    
    register_blueprints(app)
    
    register_error_handlers(app)

    return app

def configure_app(app:Flask):
    if not app.debug and not app.testing:
        # print("Setting up logging...")
        import logging
        from logging.handlers import RotatingFileHandler
        file_handler = RotatingFileHandler('tmp/flask.log', 'a', 1 * 1024 * 1024, 10)
        file_handler.setLevel(logging.DEBUG)
        app.logger.addHandler(file_handler)
        
        
def register_blueprints(app:Flask):
    from .api import tasks_route
    
    app.register_blueprint(tasks_route.tasks_bp,url_prefix='/api/tasks')
    
def register_error_handlers(app:Flask):
    @app.errorhandler(404)
    def not_found_error(error):
        print(f"404 error handler triggered,{error=}")
        return jsonify(
            code=404,
            message="Resource not found"),404
    
    @app.errorhandler(400)
    def bad_request_error(error):
        return jsonify(
            code=400,
            message="Bad request"
        ),400

    @app.errorhandler(500)
    def internal_error(error):
        return jsonify(
            code=500,              
            message="Internal server error"
        ),500

